package com.simon.study.algorithm.zheda;

import com.simon.study.algorithm.tree.Node.LNode;
import java.util.Objects;

/**
 * <p>
 *
 * @author simon
 */
public class ZLinkHash {
    LNode[]     nodes;
    int         size;
    int         capacity;


    public ZLinkHash(int capacity) {
        if(capacity < 16){ capacity = 16; }
        this.capacity = prime(capacity);
        nodes           = new LNode[this.capacity];
    }

    public int prime(int n){
        int p = (n%2) == 1 ? n+2 : n+1;

        int i = 0;
        while(true){
            for(i = (int)Math.sqrt(p); i > 2; i--){
                if( (p % i) == 0 ){ break; }
            }
            if( i==2 ){ return p; }
            p = p+ 2;
        }
    }

    public int hash(int key){
        return key % capacity;
    }


    public LNode find(int key){
        int idx = hash(key);
        LNode head = nodes[idx];
        LNode node = head;
        for(; node != null && !Objects.equals(key, node.getData()); node = node.getNext());

        return node;
    }

    public boolean insert(int key){
        LNode spot = find(key);
        if(spot == null){
            LNode item = new LNode(key);
            item.setNext(nodes[hash(key)]);
            nodes[hash(key)] = item;

            return true;
        }
        return false;
    }
}
